package by.pavlyukevich.paymentsystem.dataaccess.user.impl;

import java.util.ArrayList;
import java.util.List;

import javax.persistence.criteria.CriteriaBuilder;
import javax.persistence.criteria.CriteriaQuery;
import javax.persistence.criteria.Predicate;
import javax.persistence.criteria.Root;

import org.springframework.stereotype.Repository;

import by.pavlyukevich.paymentsystem.dataaccess.filter.Filter;
import by.pavlyukevich.paymentsystem.dataaccess.filter.IndividualFilter;
import by.pavlyukevich.paymentsystem.dataaccess.impl.AbstractDaoImpl;
import by.pavlyukevich.paymentsystem.dataaccess.user.IndividualDao;
import by.pavlyukevich.paymentsystem.datamodel.user.Individual;
import by.pavlyukevich.paymentsystem.datamodel.user.Individual_;

@Repository
public class IndividualDaoImpl extends AbstractDaoImpl<Integer, Individual> implements
		IndividualDao {

	protected IndividualDaoImpl() {
		super(Individual.class);
	}

	@Override
	public List<Individual> getList(Filter<Individual> individualFilter) {
		CriteriaQuery<Individual> criteria = getAllCriteria(individualFilter);
		addCriteriaRestrict(criteria, individualFilter);
		Root<Individual> root = getRoot(criteria, Individual.class);
		return getList(criteria, individualFilter);
	}

	@Override
	public long getCount(Filter<Individual> individualFilter) {
		CriteriaQuery<Long> criteria = getCountAllCriteria();
		addCriteriaRestrict(criteria, individualFilter);
		return getSingle(criteria);
	}

	private <T> CriteriaQuery<T> addCriteriaRestrict(CriteriaQuery<T> criteria,
			Filter<Individual> filter) {
		if (filter == null) {
			return criteria;
		}
		Root<Individual> root = getRoot(criteria, Individual.class);
		CriteriaBuilder cBuilder = getEntityManager().getCriteriaBuilder();
		List<Predicate> predicateList = new ArrayList<Predicate>();
		IndividualFilter individualFilter = (IndividualFilter) filter;
		if (individualFilter.getFamily() != null) {
			predicateList.add(cBuilder.like(root.get(Individual_.family),
					individualFilter.getFamily()));
		}
		if (individualFilter.getName() != null) {
			predicateList
					.add(cBuilder.like(root.get(Individual_.name), individualFilter.getName()));
		}

		if (predicateList.size() > 0) {
			Predicate predicateArray[] = predicateList.toArray(new Predicate[0]);
			criteria.where(predicateArray);
		}
		return criteria;
	}
}
